package cn.yll.gateway.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.yll.common.constant.MyConstants;
import cn.yll.common.exception.BsErrEnum;
import cn.yll.common.exception.BsException;
import cn.yll.common.module.RestModel;
import cn.yll.common.utils.RedisUtil;
import cn.yll.gateway.config.properties.CaptchaProperties;
import cn.yll.gateway.service.ValidateCodeService;
import cn.yll.gateway.util.StringUtils;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码实现处理
 *
 * @author ruoyi
 */
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService
{
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private CaptchaProperties captchaProperties;

    /**
     * 生成验证码
     */
    @Override
    public RestModel createCaptcha() throws IOException, BsException {
        RestModel restModel = null;
        Map<String, Object> ajax = new HashMap<>();
        boolean captchaEnabled = captchaProperties.getEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return new RestModel(RestModel.CODE_SUCCESS, RestModel.MESSAGE_SUCCESS);
        }

        // 保存验证码信息
        String uuid = IdUtil.fastSimpleUUID();
        String verifyKey = MyConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        String captchaType = captchaProperties.getType();
        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisUtil.set(verifyKey, code, MyConstants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return new RestModel(RestModel.CODE_FAIL, e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return new RestModel(ajax);
    }

    /**
     * 校验验证码
     */
    @Override
    public void checkCaptcha(String code, String uuid) throws BsException {
        if (StringUtils.isEmpty(code)) {
            throw new BsException(BsErrEnum.IMGCODE_EMPTY);
        }
        if (StringUtils.isEmpty(uuid)) {
            throw new BsException(BsErrEnum.IMGCODE_EXPIRED);
        }
        String verifyKey = MyConstants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisUtil.getV(verifyKey);

        if (!code.equalsIgnoreCase(captcha)) {
            throw new BsException(BsErrEnum.IMGCODE_ERROR);
        }
        redisUtil.delete(verifyKey);
    }
}
